package com.soccer.soccerclub.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.soccer.soccerclub.entity.Collections;
import com.soccer.soccerclub.entity.SoccerGame;
import com.soccer.soccerclub.service.CollectionService;
import com.soccer.soccerclub.service.SoccerGameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2021-04-22
 */
@RestController
@RequestMapping("/collection")
public class CollectionController {
    @Autowired
    private CollectionService collectionService;

    /**
     * 收藏
     * @param collections
     * @return
     */
    @PostMapping("/collection")
    public R collection(@RequestBody Collections collections){
        Collections one = collectionService.getOne(new LambdaQueryWrapper<Collections>().eq(Collections::getGameId, collections.getGameId()).eq(Collections::getUserId, collections.getUserId()));
        if (ObjectUtils.isNotNull(one)){
            return R.failed("你已经收藏过这个比赛了！！");
        }
        boolean save = collectionService.save(collections);
        return R.ok(save);
    }

    /**
     * 取消收藏
     * @param collections
     * @return
     */
    @PostMapping("/cancel")
    public R cancelCollection(@RequestBody Collections collections){
        Collections one = collectionService.getOne(new LambdaQueryWrapper<Collections>().eq(Collections::getGameId, collections.getGameId()).eq(Collections::getUserId, collections.getUserId()));
        if (ObjectUtils.isEmpty(one)){
            return R.failed("你已经取消收藏这个比赛了！！");
        }
        boolean remove = collectionService.remove(new LambdaQueryWrapper<Collections>().eq(Collections::getGameId, collections.getGameId()).eq(Collections::getUserId, collections.getUserId()));
        return R.ok(remove);
    }




    @Autowired
    private SoccerGameService soccerGameService;
    /**
     * 查看收藏
     * @param page
     * @param userId
     * @return
     */
    @GetMapping("/list")
    public R getMycollection(Page<Collections> page, Integer userId){
        Page page1 = collectionService.page(page,new LambdaQueryWrapper<Collections>().eq(Collections::getUserId,userId));
        List<Collections> records = page1.getRecords();
        List<SoccerGame> soccerGames = new ArrayList<>();
        for (Collections collections : records) {
            Integer gameId = collections.getGameId();
            SoccerGame soccerGame = soccerGameService.getById(gameId);
            soccerGames.add(soccerGame);
        }
        page1.setRecords(soccerGames);
        return R.ok(page1);
    }
}

